<template>
  <view class="container">
    <!-- 顶部头像区域 -->
    <view class="profile-avatar" @tap="goToProfile">
      <image :src="userInfo.userPhoto || '/static/default-avatar.png'" class="avatar"></image>
    </view>

    <!-- 词书选择区域 -->
    <view class="book-section">
      <view class="section-header">
        <text class="section-title">我的词书</text>
        <view class="manage-btn" @tap="goToBookManage">
          <uni-icons type="gear" size="20" color="#666"></uni-icons>
          <text class="manage-text">管理</text>
        </view>
      </view>
      <view class="book-list">
        <view class="book-item" v-for="book in selectedBooks" :key="book.id" @tap="selectBook(book.type)">
          <image :src="book.cover" class="book-cover"></image>
          <view class="book-info">
            <text class="book-name">{{ book.name }}</text>
            <text class="book-desc">{{ book.description }}</text>
            <view class="progress-bar">
              <view class="progress" :style="{width: book.progress + '%'}"></view>
            </view>
            <text class="progress-text">已学习 {{ book.learnedWords }}/{{ book.totalWords }} 词</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 主要功能按钮 -->
    <view class="function-buttons">
      <view class="function-button learn" @tap="goToLearn">
        <text class="button-title">Learn</text>
        <text class="button-count">{{studyWordTotal}}</text>
      </view>
      <view class="function-button review">
        <text class="button-title">Review</text>
        <text class="button-count">0</text>
      </view>
    </view>
  </view>
</template>

<script>
import {api} from '@/utils/request.js';
import {getEnumValue} from "@/utils/bookName"

export default {
  data() {
    return {
      studyWordTotal: 0,
      currentDate: '',
      userInfo: {
        userPhoto: '',
        nickname: ''
      },
      selectedBooks: [],
      todayStats: {
        wordsLearned: 86,      // 学习单词数
        wordsIncrease: 12,     // 相比昨天增加
        correctRate: 92,       // 正确率
        rateIncrease: 5,       // 正确率提升
        studyTime: 7200,       // 学习时长（秒）
        streakDays: 7          // 连续学习天数
      },
      weeklyData: [
        {
          label: '一',           // 星期几
          wordsLearned: 65,     // 单词数量
          studyTime: 3600       // 学习时长（秒）
        },
        // ... 其他天的数据
      ],
      todayDetails: [
        {
          time: '09:30',         // 学习时间
          type: '闯关模式',      // 学习模式
          wordsCount: 30,        // 学习单词数
          correctCount: 28,      // 正确数量
          duration: 15,          // 用时（分钟）
          correctRate: 93        // 正确率
        },
        // ... 其他学习记录
      ]
    }
  },
  onShow() {
    this.getSelectedBooks();
    this.updateDate()
    this.loadUserInfo()
    this.getUserProfile()
  },
  methods: {
    async getUserProfile() {
      const res = await api.getUserProfile()
      if (res.code === 200) {
        this.userInfo.userPhoto = res.result.userPhoto
      }
    },
    async getSelectedBooks() {
      const res = await api.getSelectedBooks();
      if (res.code === 200) {
        this.selectedBooks = []
        this.studyWordTotal = 0
        res.result.forEach(item => {
          const progress = ~~(item.learnedWord / item.wordTotal) * 100
          const description = `收录核心词汇${item.wordTotal}`
          const name = getEnumValue(item.bookType)
          this.studyWordTotal += item.wordTotal - item.learnedWord
          this.selectedBooks.push({
            "progress": progress,
            "name": name,
            "description": description,
            "id": item.id,
            "type": item.bookType,
            "learnedWords": item.learnedWord,
            "totalWords": item.wordTotal
          })
        })
      }

    },
    updateDate() {
      const date = new Date()
      const month = (date.getMonth() + 1).toString().padStart(2, '0')
      const day = date.getDate().toString().padStart(2, '0')
      const weekday = ['Sun.', 'Mon.', 'Tues.', 'Wed.', 'Thur.', 'Fri.', 'Sat.'][date.getDay()]
      this.currentDate = `${month}/${day} ${weekday}`
    },
    goToLearn() {
      // 检查是否有选中的词书
      if (this.selectedBooks.length === 0) {
        uni.showToast({
          title: '请先选择词书',
          icon: 'none'
        })
        return
      }

      // 如果只有一本词书，直接进入学习模式
      if (this.selectedBooks.length === 1) {
        uni.navigateTo({
          url: `/pages/word/word?book=${this.selectedBooks[0].type}`,
          fail: (err) => {
            console.error('Navigation failed:', err)
            uni.showToast({
              title: '页面跳转失败',
              icon: 'none'
            })
          }
        })
        return
      }

      // 如果有多本词书，弹出选择框
      const bookNames = this.selectedBooks.map(book => book.name)
      console.log('Available books:', bookNames)

      uni.showActionSheet({
        itemList: bookNames,
        success: (res) => {
          const selectedBook = this.selectedBooks[res.tapIndex]

          // 添加延时确保 ActionSheet 完全关闭
          setTimeout(() => {
            uni.navigateTo({
              url: `/pages/word/word?book=${selectedBook.type}`,
              success: () => {
                console.log('Navigation successful')
              },
              fail: (err) => {
                console.error('Navigation failed:', err)
                uni.showToast({
                  title: '页面跳转失败',
                  icon: 'none'
                })
              }
            })
          }, 100)
        },
        fail: (err) => {
          console.error('ActionSheet failed:', err)
        }
      })
    },
    goToProfile() {
      uni.navigateTo({
        url: '/pages/profile/profile'
      })
    },
    loadUserInfo() {
      const userInfo = uni.getStorageSync('userInfo')
      if (userInfo) {
        this.userInfo = JSON.parse(userInfo)
      }
    },
    selectBook(type) {
      this.selectedBook = type
      uni.navigateTo({
        url: `/pages/book-detail/book-detail?book=${type}`
      })
    },
    goToBookManage() {
      uni.navigateTo({
        url: '/pages/book-manage/book-manage'
      })
    }
  }
}
</script>

<style lang="scss">
.container {
  min-height: 100vh;
  background-image: linear-gradient(to bottom, #f8e5d7, #a8e6e2);
  padding: 20px;
  position: relative;
}

.profile-avatar {
  position: absolute;
  top: 40rpx;
  left: 40rpx;
  z-index: 10;

  .avatar {
    width: 80rpx;
    height: 80rpx;
    border-radius: 50%;
    border: 2rpx solid #fff;
    box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
  }
}

.book-section {
  margin-top: 150rpx;
  padding: 30rpx;
  background: rgba(255, 255, 255, 0.8);
  border-radius: 30rpx;
  backdrop-filter: blur(10px);

  .section-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 30rpx;

    .section-title {
      font-size: 36rpx;
      font-weight: bold;
      color: #333;
    }

    .manage-btn {
      display: flex;
      align-items: center;
      padding: 10rpx 20rpx;
      background: rgba(0, 0, 0, 0.05);
      border-radius: 30rpx;

      .manage-text {
        font-size: 28rpx;
        color: #666;
        margin-left: 8rpx;
      }
    }
  }

  .book-list {
    display: flex;
    flex-direction: column;
    gap: 20rpx;
  }

  .book-item {
    display: flex;
    align-items: center;
    padding: 20rpx;
    background: rgba(255, 255, 255, 0.9);
    border-radius: 20rpx;
    box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
    margin-bottom: 20rpx;

    &:active {
      transform: scale(0.98);
    }

    .book-cover {
      width: 100rpx;
      height: 140rpx;
      border-radius: 10rpx;
      margin-right: 20rpx;
      box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
    }

    .book-info {
      flex: 1;

      .book-name {
        font-size: 32rpx;
        font-weight: 500;
        color: #333;
        margin-bottom: 10rpx;
        display: block;
      }

      .book-desc {
        font-size: 24rpx;
        color: #666;
        margin-bottom: 15rpx;
      }

      .progress-bar {
        height: 6rpx;
        background: #eee;
        border-radius: 3rpx;
        margin-bottom: 10rpx;

        .progress {
          height: 100%;
          background: #4CAF50;
          border-radius: 3rpx;
          transition: width 0.3s;
        }
      }

      .progress-text {
        font-size: 24rpx;
        color: #999;
      }
    }
  }
}

.function-buttons {
  margin-top: 150rpx;
  display: flex;
  justify-content: space-between;
  gap: 20px;
}

.function-button {
  flex: 1;
  background: rgba(255, 255, 255, 0.8);
  border-radius: 15px;
  padding: 20px;
  text-align: center;

  .button-title {
    display: block;
    font-size: 18px;
    margin-bottom: 10px;
  }

  .button-count {
    display: block;
    font-size: 24px;
    color: #ff6b21;
  }

  &.review .button-count {
    color: #666;
  }
}

.tab-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  height: 50px;
  background: white;
  display: flex;
  justify-content: space-around;
  align-items: center;
  border-top: 1px solid #eee;
}

.tab-item {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;

  .tab-icon {
    width: 24px;
    height: 24px;
    margin-bottom: 4px;
  }

  .tab-text {
    font-size: 12px;
    color: #333;
  }
}
</style> 